package com.ruoyi.xqsp.controller;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.quyang.voice.utils.StringUtils;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.*;
import com.ruoyi.xqsp.domain.entity.ComicTag;
import com.ruoyi.xqsp.domain.entity.HomeComic;
import com.ruoyi.xqsp.domain.entity.HomeComicReq;
import com.ruoyi.xqsp.service.*;
import com.ruoyi.xqsp.utils.JacksonUtil;
import com.ruoyi.xqsp.utils.XqidUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 漫画操作Controller
 *
 * @author ruoyi
 * @date 2021-04-28
 */
@RestController
@Api(value = "漫画", tags = "漫画管理")
@RequestMapping("/xqsp/comic")
public class SpComicController  {
    @Autowired
    private ISpComicService spComicService;
    @Autowired
    private ISpCollectService spCollectService;
    @Autowired
    private ISpLikeService spLikeService;
    @Autowired
    private ISpComicChapterService spComicChapterService;
    @Autowired
    private ISpComicEvaluationService spComicEvaluationService;
    @Autowired
    private ISpUsersService spUsersService;
    @Autowired
    private ISpComicUserService spComicUserService;
    @Autowired
    private ISpComicBookmarkService spComicBookmarkService;
    @Autowired
    private ISpAdvertisingService spAdvertisingService;
    @Autowired
    private ISpComicTagService spComicTagService;
    @Autowired
    private ISpComicAndTagService spComicAndTagService;
    @Autowired
    private ISpChapterBuyService spChapterBuyService;
    @Autowired
    private ISpExpenseCalendarService spExpenseCalendarService;

    @Autowired
    SpComicImurlService spComicImurlService;
    @Autowired
    ComicDiscountService comicDiscountService;

    @Autowired
    SpComicWatchHistoryService comicWatchHistoryService;

    @Autowired
    SpConsumeRecordService consumeRecordService;

    /**
     * 导出漫画操作列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:comic:export')")
    @Log(title = "漫画操作", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpComic spComic) {
        List<SpComic> list = spComicService.selectSpComicList(spComic);
        ExcelUtil<SpComic> util = new ExcelUtil<SpComic>(SpComic.class);
        return util.exportExcel(list, "comic");
    }

    /**
     * 获取漫画操作详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:comic:query')")
    @GetMapping(value = "/{comicId}")
    public AjaxResult getInfo(@PathVariable("comicId") Long comicId) {
        List<SpComicAndTag> list = spComicAndTagService.selectSpComicAndTagByComicId(comicId);
        SpComicTag spComicTag;
        ComicTag comicTag = new ComicTag();
        List<Long> id = new ArrayList<>();


        for (SpComicAndTag tag : list) {
            id.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagId());

        }
        comicTag.setValue1(id);
        comicTag.setSpComic(spComicService.selectSpComicById(comicId));
        return AjaxResult.success(comicTag);
    }

    /**
     * 新增漫画操作
     */
    @PreAuthorize("@ss.hasPermi('xqsp:comic:add')")
    @Log(title = "漫画操作", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpComic spComic) {
        spComic.setComicTime(new Date());
        spComicService.insertSpComic(spComic);
        return AjaxResult.success(spComic.getComicId());
    }

    /**
//     * 修改漫画操作
//     */
//    @PreAuthorize("@ss.hasPermi('xqsp:comic:edit')")
//    @Log(title = "漫画操作", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody SpComic spComic) {
//        return toAjax(spComicService.updateSpComic(spComic));
//    }

//    /**
//     * 删除漫画操作
//     */
//    @PreAuthorize("@ss.hasPermi('xqsp:comic:remove')")
//    @Log(title = "漫画操作", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{comicIds}")
//    public AjaxResult remove(@PathVariable Long[] comicIds) {
//        return toAjax(spComicService.deleteSpComicByIds(comicIds));
//    }

    /**
     * 漫画首页
     *
     * @param homeComic
     * @return
     */
    @Log(title = "漫画首页", businessType = BusinessType.OTHER)
    @ApiOperation("漫画首页")
    @PostMapping("/getComic")
    public ResponseUtil getComic(HomeComic homeComic) {




        HashMap map = new HashMap();
        List<SpComic> spComicList1 = new ArrayList<>();

        List<SpComicTag> spComicTagList = spComicTagService.list();

        map.put("tag",spComicTagList);
//        QueryWrapper<SpComic> wrapper = new QueryWrapper();
        SpComic spComic1= new SpComic();
        spComic1.setComicSort(homeComic.getType()==0? null :homeComic.getType() );
        spComic1.setComicUnlock(homeComic.getComicUnlock()==0?null:homeComic.getComicUnlock());
        if (homeComic.getTag() != null){
            spComic1.setComicCategoryId(homeComic.getTag() == 0? null:homeComic.getTag());
        }

        spComic1.setComicStateType(homeComic.getComicStateType() == 0?null : homeComic.getComicStateType());



        PageHelper.startPage(homeComic.getPageNum(), homeComic.getPageSize());
        List<SpComic> spComicList = spComicService.selectSpComicList(spComic1);
        for (SpComic spComic:spComicList
             ) {
            spComic.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(spComic.getComicId()));
            spComic.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(spComic.getComicId()));
        }
//
//        SpComic spComic = new SpComic();
//        SpComic spComic1;

//
//        if (homeComic.getType() == 1) {//首页全部
//            List<SpComic> spComicList = spComicService.selectSpComicList(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;

//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//        if (homeComic.getType() == 2) {//最新。时间排序
//            List<SpComic> spComicList = spComicService.selectSpComicListOrderTime(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;
//                spComic1.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(comic.getComicId()));
//                spComic1.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comic.getComicId()));
//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//        if (homeComic.getType() == 3) {//人气
//            List<SpComic> spComicList = spComicService.selectSpComicListOrderWatch(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;
//                spComic1.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(comic.getComicId()));
//                spComic1.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comic.getComicId()));
//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//        if (homeComic.getType() == 4) {//韩漫
//            spComic.setComicCategory("韩漫");
//            List<SpComic> spComicList = spComicService.selectSpComicList(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;
//                spComic1.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(comic.getComicId()));
//                spComic1.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comic.getComicId()));
//
//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//        if (homeComic.getType() == 5) {//日漫
//            spComic.setComicCategory("日漫");
//            List<SpComic> spComicList = spComicService.selectSpComicList(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;
//                spComic1.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(comic.getComicId()));
//                spComic1.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comic.getComicId()));
//
//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//        if (homeComic.getType() == 6) {//国漫
//            spComic.setComicCategory("国漫");
//            List<SpComic> spComicList = spComicService.selectSpComicList(spComic);
//            TableDataInfo dataInfo = getDataTable(spComicList);
//            for (SpComic comic : spComicList) {
//                List<String> name = new ArrayList<>();
//                spComic1 = new SpComic();
//                spComic1 = comic;
//                spComic1.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(comic.getComicId()));
//                spComic1.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comic.getComicId()));
//
//                List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comic.getComicId());
//                for (SpComicAndTag tag : spComicAndTagList) {
//                    name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
//                }
//                spComic1.setComicTagName(name);
//
//                spComicList1.add(spComic1);
//            }
//            dataInfo.setRows(spComicList1);
//            return dataInfo;
//        }
//
        map.put("spComicList",PageInfo.of(spComicList));
        return ResponseUtil.success(map);
    }
    /**
     * 漫画首页
     *
     * @param homeComic
     * @return
     */
    @Log(title = "漫画搜索", businessType = BusinessType.OTHER)
    @ApiOperation("漫画搜索")
    @PostMapping("/getLikeComic")
    public ResponseUtil getLikeComic(HomeComic homeComic) {




//        QueryWrapper<SpComic> wrapper = new QueryWrapper();
        SpComic spComic1= new SpComic();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("comic_name",homeComic.getName());

        PageHelper.startPage(homeComic.getPageNum(), homeComic.getPageSize());
        List<SpComic> spComicList = spComicService.list(wrapper);
        for (SpComic spComic:spComicList
             ) {
            spComic.setChapterCount(spComicChapterService.selectSpComicChapterCountByComicId(spComic.getComicId()));
            spComic.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(spComic.getComicId()));
        }
        return ResponseUtil.success(PageInfo.of(spComicList));
    }

    /**
     * 漫画详情
     *
     * @param comicId
     * @return
     */
    @Log(title = "漫画详情", businessType = BusinessType.OTHER)
    @ApiOperation("漫画详情")
    @PostMapping("/getComicById")
    public ResponseUtil getComicById(Long comicId,Long userId) {
        HomeComicReq homeComicReq1 = new HomeComicReq();
        List<String> name = new ArrayList<>();
        SpComic spComic = new SpComic();
        spComic = spComicService.selectSpComicById1(comicId);
        spComic.setEvaluationCount(spComicEvaluationService.selectSpComicEvaluationCountById(comicId));
        QueryWrapper<SpComicChapter> queryWrapper = new QueryWrapper();
        queryWrapper.eq("comic_id",comicId);
        queryWrapper.orderByDesc("serial_number");
        queryWrapper.last("LIMIT 0,1");
        List<SpComicChapter> list = spComicChapterService.list(queryWrapper);
        if (list.size()>0){
            spComic.setComicNewChapter(list.get(0).getComicChapterName());
        }


        homeComicReq1.setSpComic(spComic);
        homeComicReq1.setSpComicList(spComicService.selectSpComicByCategory(spComicService.selectSpComicById1(comicId).getComicCategory()));
        SpComicUser spComicUser = new SpComicUser();
        spComicUser.setUserId(userId);
        spComicUser.setComicId(comicId);

        if (spComicUserService.selectSpComicUserList(spComicUser).size() == 0) {
            homeComicReq1.setComicCollect(0l);//未收藏
        }
        if (spComicUserService.selectSpComicUserList(spComicUser).size() > 0) {
            homeComicReq1.setComicCollect(1l);//已收藏
        }

        SpLike spLike = new SpLike();
        spLike.setUserId(userId);
        spLike.setLikeTypeId(comicId);
        spLike.setLikeType(2l);
        if (spLikeService.selectSpLike(spLike) == null) {
            homeComicReq1.setComicLike(0l);//位点赞
        }
        if (spLikeService.selectSpLike(spLike) != null) {
            homeComicReq1.setComicLike(1l);//已点赞
        }
        List<SpComicAndTag> spComicAndTagList = spComicAndTagService.selectSpComicAndTagByComicId(comicId);
        for (SpComicAndTag tag : spComicAndTagList) {
            name.add(spComicTagService.selectSpComicTagById(tag.getComicTagId()).getComicTagName());
        }
        homeComicReq1.setComicTagName(name);
        SpComicBookmark spComicBookmark = new SpComicBookmark();
        spComicBookmark.setUserId(userId);
        spComicBookmark.setComicId(comicId);

        if (spComicBookmarkService.selectSpComicBookmark(spComicBookmark) != null) {
            homeComicReq1.setComicChapter(spComicBookmarkService.selectSpComicBookmark(spComicBookmark).getComicChapterDirectory());

        } else {
            homeComicReq1.setComicChapter(1l);
        }
        return ResponseUtil.success(homeComicReq1);
    }

    /**
     * TODO 漫画点赞
     * @Author lipeng
     * @Date 2022/3/31 15:32
     * @param comicId
     * @param userId
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @ApiOperation("漫画点赞")
    @PostMapping("/comicLike")
    public ResponseUtil comicLike( Long comicId,Long userId) {
        SpLike spLike = new SpLike();
        spLike.setUserId(userId);
        spLike.setLikeTypeId(comicId);
        spLike.setLikeType(2l);
        if (spLikeService.selectSpLike(spLike) == null) {
            spComicService.updateSpComicByComicId(comicId);
            return ResponseUtil.update(spLikeService.insertSpLike(spLike));
        }
        if (spLikeService.selectSpLike(spLike) != null) {
            spComicService.updateSpComicByComicId1(comicId);
            return ResponseUtil.update(spLikeService.deleteSpLike(spLike));
        }

        return ResponseUtil.success();
    }

    /**
     * 漫画收藏
     *
     * @param comicId
     * @return
     */
    @Log(title = "漫画收藏", businessType = BusinessType.OTHER)
    @ApiOperation("漫画收藏")
    @PostMapping("/comicCollect")
    public ResponseUtil comicCollect( Long userId, Long comicId) {
        SpComicUser spComicUser = new SpComicUser();
        spComicUser.setUserId(userId);
        spComicUser.setComicId(comicId);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        wrapper.eq("collect_type_id",comicId);
        wrapper.eq("collect_type",2);
        SpCollect serviceOne = spCollectService.getOne(wrapper);
        if (ObjectUtils.isEmpty(serviceOne)){
            serviceOne = new SpCollect();
            serviceOne.setUserId(userId);
            serviceOne.setCollectTime(new Date());
            serviceOne.setCollectTypeId(comicId);
            serviceOne.setCollectType(2L);
            spCollectService.save(serviceOne);
        }else {
            spCollectService.removeById(serviceOne);
        }


        return ResponseUtil.success();
    }

    /**
     * 漫画评论查询
     *
     * @param homeComic
     * @return
     */
    @Log(title = "漫画评论列表", businessType = BusinessType.OTHER)
    @ApiOperation("漫画评论列表")
    @PostMapping("/getComicEvaluationV2")
    public ResponseUtil getComicEvaluation( HomeComic homeComic) {

        PageHelper.startPage(homeComic.getPageNum(), homeComic.getPageSize());
        List<SpComicEvaluation> spComicEvaluationList = spComicEvaluationService.selectSpComicEvaluationByComicId(homeComic.getComicId());
//        TableDataInfo dataInfo = getDataTable(spComicEvaluationList);
//        List<SpComicEvaluation> spComicEvaluationList1 = new ArrayList<>();
//        SpComicEvaluation spComicEvaluation;

        SpLike spLike = new SpLike();
        spLike.setUserId(homeComic.getUserId());
        spLike.setLikeType(3l);
        for (SpComicEvaluation evaluation : spComicEvaluationList) {
//            spComicEvaluation = new SpComicEvaluation();
//            spComicEvaluation = evaluation;
            spLike.setLikeTypeId(evaluation.getComicEvaluationId());
            if (spLikeService.selectSpLike(spLike) == null) {
                evaluation.setEvaluationLike(0l);//位点赞
            }
            if (spLikeService.selectSpLike(spLike) != null) {
                evaluation.setEvaluationLike(1l);//已点赞
            }
            evaluation.setUserName(spUsersService.selectSpUsersById(evaluation.getUserId()).getUserName());
//            evaluation.setUserHead(spUsersService.selectSpUsersById(evaluation.getUserId()).getUserImg());
//            spComicEvaluationList1.add(spComicEvaluation);


        }
//        dataInfo.setRows(spComicEvaluationList1);
        return ResponseUtil.success(PageInfo.of(spComicEvaluationList));
    }

    /**
     * 漫画评论查询
     *
     * @param request
     * @return
     */
//    @ApiOperation("漫画评论列表")
//    @Log(title = "漫画评论列表", businessType = BusinessType.EXPORT)
    @RequestMapping("/getComicEvaluation")
    public ResponseUtil getComicEvaluationV2(HttpServletRequest request) {

        Integer pageNum = Integer.valueOf(request.getParameter( "pageNum"));
        Integer pageSize = Integer.valueOf(request.getParameter( "pageSize"));
        Integer userId = Integer.valueOf(request.getParameter( "userId"));
        Integer comicId = Integer.valueOf(request.getParameter( "comicId"));

        PageHelper.startPage(pageNum, pageSize);
        List<SpComicEvaluation> spComicEvaluationList = spComicEvaluationService.selectSpComicEvaluationByComicId(comicId.longValue());
//        TableDataInfo dataInfo = getDataTable(spComicEvaluationList);
//        List<SpComicEvaluation> spComicEvaluationList1 = new ArrayList<>();
//        SpComicEvaluation spComicEvaluation;

        SpLike spLike = new SpLike();
        spLike.setUserId(userId.longValue());
        spLike.setLikeType(3l);
        for (SpComicEvaluation evaluation : spComicEvaluationList) {
//            spComicEvaluation = new SpComicEvaluation();
//            spComicEvaluation = evaluation;
            spLike.setLikeTypeId(evaluation.getComicEvaluationId());
            if (spLikeService.selectSpLike(spLike) == null) {
                evaluation.setEvaluationLike(0l);//位点赞
            }
            if (spLikeService.selectSpLike(spLike) != null) {
                evaluation.setEvaluationLike(1l);//已点赞
            }
            SpUsers byId = spUsersService.getById(evaluation.getUserId());
            evaluation.setUserName(byId.getUserNickname());
            evaluation.setUserImg(byId.getUserImg());
//            evaluation.setUserHead(spUsersService.selectSpUsersById(evaluation.getUserId()).getUserImg());
//            spComicEvaluationList1.add(spComicEvaluation);


        }
//        dataInfo.setRows(spComicEvaluationList1);
        return ResponseUtil.success(PageInfo.of(spComicEvaluationList));
    }

    /**
     * 评论添加
     *
     * @param spComicEvaluation
     * @return
     */
    @Log(title = "漫画评论", businessType = BusinessType.OTHER)
    @ApiOperation("漫画评论")
    @PostMapping("/addComicEvaluation")
    public ResponseUtil addComicEvaluation( SpComicEvaluation spComicEvaluation) {

        SpComicEvaluation spComicEvaluation1 = new SpComicEvaluation();
        spComicEvaluation1.setUserId(spComicEvaluation.getUserId());
        spComicEvaluation1.setComicId(spComicEvaluation.getComicId());
        spComicEvaluation1.setComicEvaluationContent(spComicEvaluation.getComicEvaluationContent());
        spComicEvaluation1.setComicEvaluationTime(new Date());

        return ResponseUtil.update(spComicEvaluationService.insertSpComicEvaluation(spComicEvaluation1));
    }

//
//    /**
//     * 漫画书架
//     *
//     * @param homeComic
//     * @return
//     */
////    @ApiOperation("漫画书架")
//    @PostMapping("/getUserComic")
//    public TableDataInfo getUserComic( HomeComic homeComic) {
//        startPages(homeComic.getPageNum(), homeComic.getPageSize());
//
//        SpComicUser spComicUser = new SpComicUser();
//        spComicUser.setUserId(homeComic.getUserId());
//        List<SpComicUser> spComicUserList = spComicUserService.selectSpComicUserList(spComicUser);
//        List<SpComicUser> spComicUserList1 = new ArrayList<>();
//        SpComicUser spComicUser1;
//        for (SpComicUser comicUser : spComicUserList) {
//            spComicUser1 = new SpComicUser();
//            spComicUser1 = comicUser;
//            spComicUser1.setSpComic(spComicService.selectSpComicById(comicUser.getComicId()));
//            spComicUserList1.add(spComicUser1);
//        }
//        return getDataTable(spComicUserList1);
//    }

    /**
     * 书架添加
     * @param homeComic
     * @return
     */
//    @PostMapping("/addUserComic")
//    public AjaxResult addUserComic(@RequestBody HomeComic homeComic){
//
//        SpComicUser spComicUser=new SpComicUser();
//        spComicUser.setComicId(homeComic.getComicId());
//        spComicUser.setUserId(homeComic.getUserId());
//        spComicUser.setComicUserTime(new Date());
//        return toAjax(spComicUserService.insertSpComicUser(spComicUser));
//
//    }

    /**
     * 漫画目录
     *
     * @param comicId
     * @return
     */

    @GetMapping("/getComicChapter/{comicId}")
    public ResponseUtil getComicChapter(@PathVariable("comicId") Long comicId,Integer pageNum,Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        List<SpComicChapter> spComicChapterList = spComicChapterService.selectSpComicChapterByComicId(comicId);
        return ResponseUtil.success(PageInfo.of(spComicChapterList));

    }

    /**
     * 漫画目录
     *
     * @param comicId
     * @return
     */

    @GetMapping("/getComicChapter")
    public ResponseUtil getComicChapter(Long comicId,Long comicChapterId,Long userId) {
        SpComic spComic = spComicService.selectSpComicById(comicId);

        if (spComic.getComicUnlock() == 2L){
            SpComicChapter comicChapter = new SpComicChapter();
            comicChapter.setComicId(comicId);
            comicChapter.setComicChapterId(comicChapterId);
            SpComicChapter spComicChapter = spComicChapterService.selectSpComicChapter(comicChapter);



            SpChapterBuy spChapterBuy = new SpChapterBuy();
            spChapterBuy.setComicChapterDirectory(spComicChapter.getComicChapterId());
            spChapterBuy.setComicId(spComicChapter.getComicId());
            spChapterBuy.setUserId(userId);
            if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size() > 0){
                return ResponseUtil.success(true);
            } else {
                return ResponseUtil.success(false);
            }

        }else {
            SpUsers spUsers = spUsersService.selectSpUserById(userId);
            if (spUsers.getUserMembersDay().compareTo(new Date())>1){
                return ResponseUtil.success(true);
            }else {
                if (spComic.getComicUnlock() == 1L){
                    return ResponseUtil.success(true);
                }else {
                    return ResponseUtil.success(false);
                }
            }
        }


    }

    /**
     * 漫画目录(前端使用)
     *
     * @return
     */
    @Log(title = "漫画目录", businessType = BusinessType.OTHER)
    @ApiOperation("漫画目录")
    @PostMapping("/getComicChapterInfo")
    public ResponseUtil getComicChapter( SpGetComicChapterInfo spGetComicChapterInfo) {
        PageHelper.startPage(spGetComicChapterInfo.getPageNum(),spGetComicChapterInfo.getPageSize());
        List<SpComicChapter> spComicChapterList = spComicChapterService.selectSpComicChapterByComicId(spGetComicChapterInfo.getComicId());
//        List<SpComicChapter> spComicChapterList = spComicChapterService.selectSpComicChapterByComicId(spGetComicChapterInfo.getComicId());
        SpChapterBuy spChapterBuy;//购买章节记录
        SpUsers users;
        for (SpComicChapter spComicChapter : spComicChapterList) {
            spChapterBuy = new SpChapterBuy();
            spChapterBuy.setComicChapterDirectory(spComicChapter.getComicChapterId());
            spChapterBuy.setComicId(spComicChapter.getComicId());
            spChapterBuy.setUserId(spGetComicChapterInfo.getUserId());

            switch (spComicChapter.getComicIsFree()){
                case 1:
                    spComicChapter.setBUnlock(true);
                    break;
                case 2:
                    users = spUsersService.selectSpUserById(spGetComicChapterInfo.getUserId());
                    if (users != null) {
                        if (DateUtil.compare(users.getUserMembersDay(),new Date())>0){
                            spComicChapter.setBUnlock(true);
                        }else {
                            spComicChapter.setBUnlock(false);
//                            if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size() > 0){
//                                spComicChapter.setBUnlock(true);
//                            } else {
//                                spComicChapter.setBUnlock(false);
//                            }

                        }


//                        spComicChapter.setBUnlock(true);
                    }else {
                        spComicChapter.setBUnlock(false);
                    }


                    break;
                case 3:
                    if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size() > 0){
                        spComicChapter.setBUnlock(true);
                    } else {
                        spComicChapter.setBUnlock(false);
                    }

                    break;

            }

        }
        return ResponseUtil.success(PageInfo.of(spComicChapterList));
    }

//    漫画阅读历史

    @Log(title = "漫画阅读记录", businessType = BusinessType.OTHER)
    @ApiOperation("漫画阅读记录")
    @PostMapping("/comicReadingRecord")
    public ResponseUtil comicReadingRecord(Long userId,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<SpComicWatchHistory> wrapper =new QueryWrapper();
//        wrapper.eq("comic_watch_history_type_id",homeComic.getComicId());
        wrapper.eq("user_id",userId);
        wrapper.orderByDesc("comic_watch_history_time");

        List<SpComicWatchHistory> list = comicWatchHistoryService.list(wrapper);
        for (SpComicWatchHistory spComicWatchHistory:
             list) {
            spComicWatchHistory.setComic(spComicService.getById(spComicWatchHistory.getComicWatchHistoryTypeId()));

        }
        return ResponseUtil.success(PageInfo.of(list));
    }

    @Log(title = "清空漫画阅读记录", businessType = BusinessType.OTHER)
    @ApiOperation("清空漫画阅读记录")
    @PostMapping("/delComicReadingRecord")
    public ResponseUtil comicReadingRecord(Long userId,Long id){

        if (id != null){
            comicWatchHistoryService.removeById(id);
        }   else {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",userId);
            comicWatchHistoryService.remove(wrapper);
        }

        return ResponseUtil.success();
    }

    /**
     * 阅读
     *
     * @param homeComic
     * @return
     */
    @Transactional
    @ApiOperation("漫画阅读")
    @Log(title = "漫画阅读", businessType = BusinessType.OTHER)
    @PostMapping("/getComicChapterImg")
    public ResponseUtil getComicChapterImg( HomeComic homeComic) {

        //查询是否会员
        SpUsers spUsers = spUsersService.getOne(new QueryWrapper<SpUsers>().eq("user_id", homeComic.getUserId()));

        if (homeComic.getUserId() !=null){
            QueryWrapper wrapper =new QueryWrapper();
            wrapper.eq("comic_watch_history_type_id",homeComic.getComicId());
            wrapper.eq("user_id",homeComic.getUserId());
            SpComicWatchHistory historyServiceOne = comicWatchHistoryService.getOne(wrapper);
            if (historyServiceOne == null){
                SpComicWatchHistory spComicWatchHistory = new SpComicWatchHistory();
                spComicWatchHistory.setUserId(homeComic.getUserId());
                spComicWatchHistory.setComicWatchHistoryTypeId(homeComic.getComicId());
                spComicWatchHistory.setComicWatchHistoryChapterId(homeComic.getComicChapterId());
                comicWatchHistoryService.save(spComicWatchHistory);
            }else {
                historyServiceOne.setComicWatchHistoryChapterId(homeComic.getComicChapterId());
                historyServiceOne.setComicWatchHistoryTime(new Date());
                comicWatchHistoryService.updateById(historyServiceOne);
            }
        }



        //漫画详情
        SpComic spComic = spComicService.getOne(new QueryWrapper<SpComic>().eq("comic_id", homeComic.getComicId()));
        List<SpComicImurl> spComicImurls = new ArrayList<>();
        SpComicChapter comicChapter = spComicChapterService.getById(homeComic.getComicChapterId());
        SpChapterBuy spChapterBuy = new SpChapterBuy();//购买章节记录
        spChapterBuy.setComicId(homeComic.getComicId());
        spChapterBuy.setUserId(homeComic.getUserId());
        SpChapterBuy one = new SpChapterBuy();
        switch (comicChapter.getComicIsFree().intValue()){

            //免费章节 直接阅读
            case 1:
                PageHelper.startPage(homeComic.getPageNum(),homeComic.getPageSize());
                spComicImurls = spComicImurlService.orderList( homeComic.getComicChapterId(), homeComic.getComicId());

                break;
//            付费章节  购买阅读
            case 3:



                spChapterBuy.setComicChapterDirectory(homeComic.getComicChapterId());
                 one = spChapterBuyService.getOne(new QueryWrapper<SpChapterBuy>().eq("user_id", homeComic.getUserId()).eq("comic_id", homeComic.getComicId()).eq("comic_chapter_directory", homeComic.getComicChapterId()));
                if (ObjectUtils.isEmpty(one)){

                    if (spComic.getComicUnlockGlod().compareTo(spUsers.getUserGlod()) > -1){
                        return ResponseUtil.fail("余额不足");
                    }
                    spChapterBuy.setComicChapterDirectory(homeComic.getComicChapterId() );
                    //保存购买记录
                    spChapterBuyService.save(spChapterBuy);

                    spUsers.setUserGlod(spUsers.getUserGlod() .subtract(spComic.getComicUnlockGlod()) );
                    spUsersService.updateSpUsers(spUsers);
                }

                SpConsumeRecord consumeRecord = new SpConsumeRecord();
                consumeRecord.setMoney(spComic.getComicUnlockGlod());
                consumeRecord.setTradeNo(StringUtils.generateOrderNumber());
                consumeRecord.setPayType(2);
                consumeRecord.setUserId(homeComic.getUserId());
                consumeRecord.setCurrentBalance(spUsers.getUserGlod());
                consumeRecord.setChangeType(2);
                consumeRecord.setType(11);
                consumeRecord.setOperationAmount(spComic.getComicUnlockGlod());
                consumeRecord.setCreateTime(new Date());
                consumeRecord.setDescs("漫画购买");
                consumeRecordService.save(consumeRecord);



                PageHelper.startPage(homeComic.getPageNum(),homeComic.getPageSize());
//                spComicImurls = spComicImurlService.list(new QueryWrapper<SpComicImurl>().eq("comic_chapter_id", homeComic.getComicChapterId()).eq("comic_id", homeComic.getComicId()));
                spComicImurls = spComicImurlService.orderList( homeComic.getComicChapterId(), homeComic.getComicId());

                break;

//                会员章节  免费阅读
            case 2:
                if (spUsers.getUserMembersDay().compareTo(new Date()) < 0){
                    one = spChapterBuyService.getOne(new QueryWrapper<SpChapterBuy>().eq("user_id", homeComic.getUserId()).eq("comic_id", homeComic.getComicId()).eq("comic_chapter_directory", homeComic.getComicChapterId()));
                    if (ObjectUtils.isEmpty(one)){

                        if (spComic.getComicUnlockGlod().compareTo(spUsers.getUserGlod()) > -1){
                            return ResponseUtil.fail("余额不足");
                        }

                        spChapterBuy.setComicChapterDirectory(homeComic.getComicChapterId() );
                        //保存购买记录
                        spChapterBuyService.save(spChapterBuy);

                        spUsers.setUserGlod(spUsers.getUserGlod() .subtract(spComic.getComicUnlockGlod()));
                        spUsersService.updateSpUsers(spUsers);

                        SpConsumeRecord consumeRecord2 = new SpConsumeRecord();
                        consumeRecord2.setMoney(spComic.getComicUnlockGlod());
                        consumeRecord2.setTradeNo(StringUtils.generateOrderNumber());
                        consumeRecord2.setPayType(2);
                        consumeRecord2.setUserId(homeComic.getUserId());
                        consumeRecord2.setCurrentBalance(spUsers.getUserGlod());
                        consumeRecord2.setChangeType(2);
                        consumeRecord2.setType(11);
                        consumeRecord2.setOperationAmount(spComic.getComicUnlockGlod());
                        consumeRecord2.setCreateTime(new Date());
                        consumeRecord2.setDescs("漫画购买");
                        consumeRecordService.save(consumeRecord2);


                        PageHelper.startPage(homeComic.getPageNum(),homeComic.getPageSize());
//                spComicImurls = spComicImurlService.list(new QueryWrapper<SpComicImurl>().eq("comic_chapter_id", homeComic.getComicChapterId()).eq("comic_id", homeComic.getComicId()));
                        spComicImurls = spComicImurlService.orderList( homeComic.getComicChapterId(), homeComic.getComicId());
                    }else {
                        PageHelper.startPage(homeComic.getPageNum(),homeComic.getPageSize());
//                spComicImurls = spComicImurlService.list(new QueryWrapper<SpComicImurl>().eq("comic_chapter_id", homeComic.getComicChapterId()).eq("comic_id", homeComic.getComicId()));
                        spComicImurls = spComicImurlService.orderList( homeComic.getComicChapterId(), homeComic.getComicId());
                    }

//                    return ResponseUtil.fail("您还不是会员");
                }else {
                    PageHelper.startPage(homeComic.getPageNum(),homeComic.getPageSize());
//                spComicImurls = spComicImurlService.list(new QueryWrapper<SpComicImurl>().eq("comic_chapter_id", homeComic.getComicChapterId()).eq("comic_id", homeComic.getComicId()));
                    spComicImurls = spComicImurlService.orderList( homeComic.getComicChapterId(), homeComic.getComicId());
                }
                break;
        }

        SpComicBookmark spComicBookmark = new SpComicBookmark();//书签
        spComicBookmark.setUserId(homeComic.getUserId());
        spComicBookmark.setComicId(homeComic.getComicId());
        spComicService.updateWatchByComicId(homeComic.getComicId());


        SpExpenseCalendar spExpenseCalendar = new SpExpenseCalendar();//消费记录
        spExpenseCalendar.setExpenseCalendarTime(new Date());
        spExpenseCalendar.setExpenseCalendarState(homeComic.getComicId());
        spExpenseCalendar.setUserId(homeComic.getUserId());
        spExpenseCalendar.setExpenseCalendarOrder(XqidUtils.generateOrderId());
        spExpenseCalendar.setExpenseCalendarWay(2);
        spExpenseCalendar.setExpenseCalendarGlod(spComic.getComicUnlockGlod());
        spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar);




        return ResponseUtil.success(PageInfo.of(spComicImurls));
    }


//    /*
    @Transactional
    @ApiOperation("漫画购买计算")
    @Log(title = "漫画购买计算", businessType = BusinessType.OTHER)
    @PostMapping("/buyComicsCalculate")
    public ResponseUtil buyComicsCalculate(Long userId ,Long comicId,Integer serialNumber, Integer id ) {



        //查询是否会员
        SpUsers spUsers = spUsersService.getOne(new QueryWrapper<SpUsers>().eq("user_id", userId));

        ComicDiscount comicDiscount = comicDiscountService.getById(id);

        //漫画详情
        SpComic spComic = spComicService.getOne(new QueryWrapper<SpComic>().eq("comic_id", comicId));
        BigDecimal multiply = new BigDecimal("0");
//        if (spComic.getComicUnlock() !=2L  ){
////            return ResponseUtil.fail("该漫画不是金币付费");
//            return ResponseUtil.success(multiply.setScale(2,BigDecimal.ROUND_UP) );
//        }
//

        SpChapterBuy spChapterBuy = new SpChapterBuy();//购买章节记录
        spChapterBuy.setComicId(comicId);
        spChapterBuy.setUserId(userId);

        List<SpComicChapter> spComicChapters = spComicChapterService.selectSerialNumber(comicId, serialNumber, comicDiscount.getValue());

        BigDecimal money = BigDecimal.ZERO;
        SpChapterBuy one = new SpChapterBuy();
        for (SpComicChapter spComicChapter:spComicChapters
             ) {
            switch (spComicChapter.getComicIsFree()){
                case 1:
                    break;
                case 3:


                     one = spChapterBuyService.getOne(new QueryWrapper<SpChapterBuy>().eq("user_id", userId).eq("comic_id", comicId).eq("comic_chapter_directory", spComicChapter.getComicChapterId()));

                    if (ObjectUtils.isEmpty(one)){
                        money = spComic.getComicUnlockGlod().add(money);
                    }

                    break;
                case 2:
                    if (spUsers.getUserMembersDay().compareTo(new Date()) < 0 ){
                        return ResponseUtil.fail("请开通会员");
                    }


                    break;
            }


        }

         multiply = money.multiply(BigDecimal.valueOf(comicDiscount.getDiscount()));
        return ResponseUtil.success(multiply.setScale(0,BigDecimal.ROUND_UP) );
    }

    public static void main(String[] args) {
        SpUsers spUsers = new SpUsers();
        spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),-1));
        System.out.println("spUsers.getUserMembersDay() = " + spUsers.getUserMembersDay());
        System.out.println(spUsers.getUserMembersDay().compareTo(new Date()));

    }

    @Transactional
    @ApiOperation("漫画购买")
    @Log(title = "漫画购买", businessType = BusinessType.OTHER)
    @PostMapping("/buyComics")
    public ResponseUtil buyComics(Long userId ,Long comicId,Integer serialNumber, Integer id,Integer buyType ) {

        if (buyType == 1){
            spUsersService.updateSpUsersBuyTypeById(userId);
        }else if (buyType == 0){
            spUsersService.updateSpUsersBuyTypeById1(userId);
        }


        //查询是否会员
        SpUsers spUsers = spUsersService.getOne(new QueryWrapper<SpUsers>().eq("user_id", userId));

        ComicDiscount comicDiscount = comicDiscountService.getById(id);

        //漫画详情
        SpComic spComic = spComicService.getOne(new QueryWrapper<SpComic>().eq("comic_id", comicId));
        List<SpComicImurl> spComicImurls = new ArrayList<>();


        List<SpComicChapter> spComicChapters = spComicChapterService.selectSerialNumber(comicId, serialNumber, comicDiscount.getValue());
        BigDecimal money = BigDecimal.ZERO;
        ArrayList<SpChapterBuy> list = new ArrayList<>();
        SpChapterBuy one = new SpChapterBuy();
        for (SpComicChapter spComicChapter:spComicChapters
        ) {
            SpChapterBuy spChapterBuy = new SpChapterBuy();//购买章节记录
            spChapterBuy.setComicId(comicId);
            spChapterBuy.setUserId(userId);
            switch (spComicChapter.getComicIsFree()){
                case 1:
                    break;
                case 3:
                        one = spChapterBuyService.getOne(new QueryWrapper<SpChapterBuy>().eq("user_id", userId).eq("comic_id", comicId).eq("comic_chapter_directory", spComicChapter.getComicChapterId()));
                    if (ObjectUtils.isEmpty(one)){
                        money = spComic.getComicUnlockGlod().add(money);
                        spChapterBuy.setComicChapterDirectory(spComicChapter.getComicChapterId());
//                        money += spComic.getComicUnlockGlod();
                        list.add(spChapterBuy);
                    }
                    break;
                case 2:
                    if (spUsers.getUserMembersDay().compareTo(new Date()) < 0 ){
                        return ResponseUtil.fail("请开通会员");
                    }

                    break;
            }



        }


        BigDecimal multiply = money.multiply(BigDecimal.valueOf(comicDiscount.getDiscount()));
        BigDecimal bigDecimal = multiply.setScale(0, BigDecimal.ROUND_UP);

        if (bigDecimal.compareTo(spUsers.getUserGlod()) > -1 ){
            return ResponseUtil.fail("余额不足");
        }

        SpConsumeRecord consumeRecord = new SpConsumeRecord();
        consumeRecord.setMoney(bigDecimal);
        consumeRecord.setTradeNo(StringUtils.generateOrderNumber());
        consumeRecord.setPayType(2);
        consumeRecord.setUserId(userId);
        consumeRecord.setCurrentBalance(spUsers.getUserGlod());
        consumeRecord.setChangeType(2);
        consumeRecord.setType(11);
        consumeRecord.setOperationAmount(spComic.getComicUnlockGlod());
        consumeRecord.setCreateTime(new Date());
        consumeRecord.setDescs("漫画购买");
        consumeRecordService.save(consumeRecord);


        spChapterBuyService.saveBatch(list);

        spUsers.setUserGlod(spUsers.getUserGlod() .subtract(bigDecimal) );
        spUsersService.updateSpUsers(spUsers);


        return ResponseUtil.success();
    }


    /**
     * 漫画页banner图
     *
     * @return
     */
    @Log(title = "漫画分类", businessType = BusinessType.OTHER)
    @ApiOperation("漫画分类")
    @GetMapping("/comicCategory")
    public ResponseUtil comicCategory() {
        List<SpComicTag> spComicTagList = spComicTagService.list();
        return ResponseUtil.success(spComicTagList);
    }


    /**
     * 漫画页banner图
     *
     * @return
     */
    @ApiOperation("漫画页banner图")
    @GetMapping("/getComicBanner")
    public AjaxResult getComicBanner() {
        return AjaxResult.success(spAdvertisingService.selectSpAdvertisingByComic());
    }

    /**
     * 用户开关漫画自动购买
     *
     * @param userId
     * @return
     */
    @Log(title = "用户开关漫画自动购买", businessType = BusinessType.OTHER)
    @ApiOperation("用户开关漫画自动购买")
    @GetMapping("/updateBuyType")
    public ResponseUtil updateBuyType(@RequestParam(value = "userId", required = false) Long userId,Integer type) {
        SpUsers spUsers = new SpUsers();
        spUsers.setUserId(userId);
        spUsers.setUserBuyType(type);
        spUsersService.updateById(spUsers);

        return ResponseUtil.success();
    }

}
